package servlet;


import bean.UserInfo;
import org.json.JSONObject;
import pojo.Comment;
import bean.Main;
import pojo.Post;
import pojo.Star;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.List;


public class MainPostServlet extends HttpServlet {
    public static int USER_POSTS = 123;
    public static int STAR_POSTS = 321;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject obj = new JSONObject(req.getParameter("result"));
        int star = obj.getInt("star");
        int end = obj.getInt("end");
        RedisDao redisDao = new RedisDaoImpl();
        //        拿到排好序的end-star条postId
        List<String> postList = null;
        int count = 0;
        String type = req.getParameter("type");
        if (type != null) {
            int a = Integer.valueOf(type);
            int account = Integer.valueOf(req.getParameter("account"));
            switch (a) {
                case 123:
                    postList = redisDao.getUserPost(account, star, end);
//            获取用户发布帖子的总数
                    count = redisDao.userPostCount(account);
                    System.out.println(count);
                    break;
                case 321:
                    postList = redisDao.getUserStar(account, star, end);
                    System.out.println(postList.toString());
//            获取用户发布帖子的总数
                    count = redisDao.starPostCount(account);
                    System.out.println(count);
                    break;
                default:
            }
        } else {
            postList = redisDao.getPostId(star, end);
            count = redisDao.postCount();
        }


        JSONObject obj1 = new JSONObject();

        List<Main> list = new ArrayList<>();
        for (String postId : postList) {
            Main main = new Main();
            Post post = redisDao.getPost(Integer.valueOf(postId));
            int ant = post.getPostAccount();
            UserInfo userInfo = redisDao.getUserInfo(ant);

//            帖子对应的评论信息
            List<Comment> comments = redisDao.getCom(Integer.valueOf(postId));
//            帖子对应的点赞信息
            List<Star> stars = redisDao.getStar(Integer.valueOf(postId));
            main.setPost(post);
            main.setComments(comments);
            main.setStars(stars);
            main.setUserInfo(userInfo);
            list.add(main);
        }
//        获取帖子的数量
        obj1.put("main", list);
        obj1.put("count", count);
//          设置响应内容类型
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(obj1);
    }
}
